import axios from 'axios'
import { createAlova } from 'alova'
import VueHook from 'alova/vue'
import { axiosRequestAdapter } from '@alova/adapter-axios'

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: '/api/v1', // 使用相对路径以利用Vite代理
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: false // 禁用凭证以避免CORS问题
})

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // 不再在这里提取response.data，让Alova来处理
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 创建Alova实例
export const alovaInstance = createAlova({
  baseURL: '/api/v1', // 使用相对路径以利用Vite代理
  statesHook: VueHook,
  requestAdapter: axiosRequestAdapter(),
  beforeRequest: (method) => {
    // 在请求发送前添加认证头
    const token = localStorage.getItem('token')
    if (token) {
      method.config.headers = {
        ...method.config.headers,
        Authorization: `Bearer ${token}`
      }
    }
  },
  responded: {
    onSuccess: async (response: any) => {
      console.log('Alova response:', response)
      // 检查response是否是Axios响应对象
      if (response && response.data !== undefined) {
        console.log('Returning response.data:', response.data)
        return response.data
      }
      // 如果不是Axios响应对象，直接返回response
      console.log('Returning raw response:', response)
      return response
    },
    onError: (error: any) => {
      console.error('Alova error:', error)
      
      // 检查是否是网络错误
      if (error.code === 'ECONNABORTED' || error.message.includes('Network Error')) {
        error.code = 'NETWORK_ERROR';
      }
      
      // 检查是否是401错误
      if (error.message.includes('401') || error.response?.status === 401) {
        // token过期或无效，清除本地存储并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        window.location.href = '/login'
      }
      throw error
    }
  }
})

export default axiosInstance